package com.txh.blog.filter;

import com.txh.blog.consts.Consts;
import com.txh.blog.model.UserInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

public class UserInfoStatuFilter implements Filter {
    public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
    private String excludesPattern;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter(PARAM_NAME_EXCLUSIONS);
        if (param != null && param.trim().length() !=0){
            excludesPattern = param;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest =(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
        //获取session中用户判断状态
        UserInfo userInfo = (UserInfo) httpServletRequest.getSession().getAttribute(Consts.SESSION_USER);
        //不需要过滤的页面
        String path= httpServletRequest.getRequestURI().substring(httpServletRequest.getRequestURI().lastIndexOf("/"),httpServletRequest.getRequestURI().length());

        if (excludesPattern.indexOf(path) >-1){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if (userInfo == null){
            //跳转到登陆页
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/back");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
    }

    @Override
    public void destroy() {

    }
}
